package com.rykj

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import com.rykj.util.LogX
import java.util.*

object ActivityManagement : Application.ActivityLifecycleCallbacks {

    private var foregroundActivities = 0

    /**是否在前台*/
    var isForeground = false

    public val activityStacks = Vector<Activity>()

    override fun onActivityPaused(activity: Activity?) {
    }

    override fun onActivityResumed(activity: Activity?) {
    }

    override fun onActivityStarted(activity: Activity?) {
        foregroundActivities++
        if (foregroundActivities == 1) {
            isForeground = true
            LogX.e("ycw", "App置于前台 ")
        }
    }

    override fun onActivityDestroyed(activity: Activity?) {
        popActivity(activity)
    }

    override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
    }

    override fun onActivityStopped(activity: Activity?) {
        foregroundActivities--
        if (foregroundActivities == 0) {
            isForeground = false
            LogX.e("ycw", "App置于后台 ")
        }
    }

    override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
        pushActivity(activity)
    }


    /**
     * 判断activity是否在运行
     */
    fun containsActivity(cls: Class<*>): Boolean {
        for (activityStack in activityStacks) {
            if (activityStack.javaClass.name == cls.name) {
                return true
            }
        }
        return false
    }

    fun pushActivity(activity: Activity?) {
        if (!activityStacks.contains(activity)) {
            activityStacks.add(activity)
        }
    }

    fun popActivity(activity: Activity?) {
        activityStacks.remove(activity)
    }

    fun showActivity(activity: Class<*>) {
        val application = AppProxy.application
        val intent = Intent(application?.applicationContext, activity)
        application?.startActivity(intent)
    }

    fun exitApp() {
        for (activity in activityStacks) {
            activity.finish()
        }
        activityStacks.clear()
    }

    fun exitApp(exceptActivity: String) {
        for (activity in activityStacks) {
            if (activity.localClassName != exceptActivity) {
                activity.finish()
            }
        }
        activityStacks.clear()
    }

}